package com.zll.dms.utils;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.zll.dms.constants.Constants;
import com.zll.dms.exception.MyBaseException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * 七牛云工具类
 */
@Slf4j
public class QiniuUtils {
    /**
     * 获取token
     * @return
     */
    private static String getUpToken() {
        Auth auth = Auth.create(Constants.QN_ACCESSKEY, Constants.QN_SECRETKEY);
        return auth.uploadToken(Constants.QN_BUCKET);
    }

    /**
     * 上传文件
     * @param file
     * @return
     */
    public static String uploadFile(MultipartFile file) {
        String token = getUpToken();
        if(StringUtils.isBlank(token)) {
            log.error("上传文件至七牛云-未获取到token，请重试！");
            return null;
        }
        byte[] bytes = null;
        try {
            bytes = file.getBytes();
        } catch (IOException e) {
            log.error("上传文件至七牛云-获取MultipartFile字节数组错误",e);
            throw new MyBaseException("上传失败");
        }
        Configuration configuration = new Configuration();
        UploadManager uploadManager = new UploadManager(configuration);
        Response response = null;
        String originalFilename = file.getOriginalFilename();
        String suff = StringUtils.substringAfterLast(originalFilename, ".");
        String newName = UUID.randomUUID().toString() + "." + suff;
        try {
            response = uploadManager.put(bytes, newName, token);
        } catch (QiniuException e) {
            log.error("上传文件至七牛云-上传时报错");
            throw new MyBaseException("上传失败");
        }
        if (response.isOK()) {
            return "http://" + Constants.QN_DOMAIN + "/" + newName;
        }
        throw new MyBaseException("上传失败");
    }
}
